package dao;

import bean.User;
import utills.HiveJdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Keven-赵仕星
 * @date 2022/6/7 23:09
 */
public class QueryIndividual {

    static Connection connection;

    public QueryIndividual() {
        try {
            Connection connection = HiveJdbc.getConnection();
            if (connection != null)
                System.out.println("connect success");
            else
                System.out.println("connect fail");
            this.connection = connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<User> queryIndividual(User searchUser) throws Exception {
        QueryIndividual queryUser = new QueryIndividual();
        Statement stmt = connection.createStatement();
        String sql = "select * from student";
        ResultSet rus = stmt.executeQuery(sql);

        List<User> users = new ArrayList<>();
        while (rus.next()) {
            int id = Integer.parseInt(rus.getString("id"));
            String name = rus.getString("name");
            String date = rus.getString("date");
            String phone = rus.getString("phone");
            int semester = rus.getInt("semester");
            String state = rus.getString("state");
            String sex=rus.getString("sex");
            Boolean b = true;

            if (!"null".equals(String.valueOf(searchUser.getId()))) {
                if (searchUser.getId() != id) b = false;
            }
            if (!searchUser.getName().isEmpty() && (b == true)) {
                if (!name.equals(searchUser.getName())) b = false;
            }
            if (!searchUser.getDate().isEmpty() && (b == true)) {
                if (!date.equals(searchUser.getDate())) b = false;
            }
            if (!searchUser.getPhone().isEmpty() && (b == true)) {
                if (!phone.equals(searchUser.getPhone())) b = false;
            }
            if (!"null".equals(String.valueOf(searchUser.getSemester()))) {
                if (searchUser.getSemester() != semester) b = false;
            }
            if (!searchUser.getState().isEmpty() && (b == true)) {
                if (!state.equals(searchUser.getState())) b = false;
            }

            if (b) {
                User user = new User();
                user.setId(id);
                user.setName(name);
                user.setDate(date);
                user.setPhone(phone);
                user.setSemester(semester);
                user.setState(state);
                user.setSex(sex);

                users.add(user);
            }
        }
        HiveJdbc.close(stmt, connection);
        return users;
    }
}
